import '../public/index'
import url from '../data/url'
import request from '../data/request'
import { tableConfig, header } from '../data/config'
import { getUrlParam, random_string, get_suffix, fetch2, previewImg, imgPreviewModal } from '../data/util'
import { aliyun } from '../data/config'
// 引入验证规则，只能输入字符和数字
import { deviceCode } from '../data/validate'
import store from 'store'
// 这个更改规则不变化之前的规则
const cusId = deviceCode

const type = getUrlParam('type')
const tabIndex = getUrlParam('tab')

const base = url.base
const detailUrl = '/admin/equipmentInfo/v2/detail.json.json'
const UseHis = '/admin/equipmentInfo/facadeUseRecords.json'
const codeList = '/admin/equipmentInfo/activationCode.json'
const addCodeUrl = '/admin/equipmentInfo/doAddActivationCode.json'
const getTemplateInfoUrl = 'admin/equipmentInfo/getTempleteInfo.json'
const getServiceTypeDefaultDataUrl = 'admin/equipmentInfo/serviceTypeObject.json'
const getBuyTemplatUrl = '/admin/equipmentInfo/getListTemplet.json'
const startValidateUrl = '/admin/equipmentInfo/verification.json'
const startDevUrl = 'admin/applyRecord/commitApply.json'
const detailMore = 'admin/equipmentInfo/v2/recordDetail.json'
const getBuildListUrl = 'admin/equipmentInfo/getProperty.json'
const ytjKeyboardUrl = 'admin/equipmentInfo/getKeyBorad.json'
const posKeyboardUrl = 'admin/equipmentInfo/getIntelligentPosInfo.json'
const getIntelligenName = 'admin/equipmentInfo/getIntelligenName.json'

let table

// 注册select2组件
Vue.component('v-select', VueSelect.VueSelect)
const vueApp = new Vue({
  data: {
    isPaymentType: null, //当终端类型type（2：拉卡拉，3：银商）为2时需要选择激活码，为3时隐藏激活码
    type: type,
    buildList: null,
    propertyArea: '选择楼盘',
    serviceType: null,
    cancelDeposit: 0,  // 是否支持取消存款证明
    refundReceiveSMSPhone: null,  // 退款通知手机号
    isShowName: 1,
    isLock: 0,
    lockTime: '',
    lockTimeList: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
    lockImgPreview: null,
    lockImgProgress: 0,
    lockImg: '',
    islockImgLock: false,
    isSignature: 1,
    templetId: null,
    templetList: null,
    ylTicketCount: 1,
    printNum: 1,
    posSignature: 1,
    showBankInfo: 1,
    buyTemplateList: null,
    propertyAddress: null,
    voucher: null,
    overdueTime: null,
    orderOverdueTime: null,
    agreement: 1,
    keyPos: '选择激活码',
    keyYtj: '选择键盘',
    keyBoardList: null,
    imark: null,
    mchName: null,
    isPhotograph: null,
    isOpenOcr: null,
    changePosLowestMoney: 0,
    changePosPay: 0,
    isPrintQRCode: 0
  },
  computed: {
    // 键盘码或者激活码
    keyBoardOrPosinfo() {
      console.log('keyYtj===>>', this.keyYtj)
      if (this.type === 'ytj') {
        if (this.keyYtj) {
          return this.keyYtj.keySn
        }
      }
      if (this.type === 'pos') {
        if (this.keyPos) {
          return this.keyPos.keySn
        }
      }
    },
    keyBoardIdOrPosinfoId() {
      if (this.type === 'ytj') {
        if (this.keyYtj) {
          return this.keyYtj.idStr
        }
      }
      if (this.type === 'pos') {
        if (this.keyPos) {
          return this.keyPos.idStr
        }
      }
    },
    propertyId() {
      if (this.propertyArea) {
        return this.propertyArea.id
      }
      return ''
    },
    propertyAreaId() {
      if (this.propertyArea) {
        const area = this.propertyArea.propertyArea
        let propertyArea
        switch (area) {
          case 'hd':
            propertyArea = '华东'
            break
          case 'hn':
            propertyArea = '华南'
            break
          case 'hx':
            propertyArea = '华西'
            break
          case 'hb':
            propertyArea = '华北'
            break
          case 'hz':
            propertyArea = '华中'
            break
        }
        return {
          id: this.propertyArea.id,
          propertyName: this.propertyArea.propertyName,
          propertyArea: propertyArea,
          channelName: this.propertyArea.channelName
        }
      }
      return ''
    },
    channelName() {
      if (this.propertyArea) {
        return this.propertyArea.channelName
      }
      return ''
    }
  },
  watch: {
    // serviceType和propertyAreaId做脏检测，都对应才查询模版
    serviceType(val) {
      let data
      if (this.propertyId) {
        data = {
          buildInfoId: this.propertyId,
          serviceType: val
        }
      }
      if (val === 'ckzm') {
        this.getTemplateInfoUrl()
      } else if (val === 'xf') {
        if (this.type === 'ytj') {
          // 获取认购书
          this.getBuyTemplateList()
        }
      }
      this.getServiceTypeDefaultData(data)
    },
    propertyAreaId(val) {
      if (val && this.serviceType === 'ckzm') {
        const data = {
          buildInfoId: val.id,
          serviceType: 'ckzm'
        }
        this.getServiceTypeDefaultData(data)
      } else {
        const data = {
          buildInfoId: this.propertyId,
          serviceType: this.serviceType
        }
        this.getServiceTypeDefaultData(data)
      }
    },
    keyBoardIdOrPosinfoId(val) {
      if (val != '选择键盘') {
        fetch2(getIntelligenName, { IntellingenId: val }).then(res => {
          if (res) {
            this.mchName = res.mchName
          }
        })
      }
    }
  },
  created() {
    this.getBuildingList()
    this.getKeyBoardOrPosinfo()
  },
  methods: {
    imgPreviewModal: imgPreviewModal,
    // 锁屏图片上传
    uploadLockImg: function () {

      let that = this,
        file = this.$refs.lockImg.files[0];

      if (!file) {
        layer.msg('没有选择文件', {
          icon: 5
        })

        return
      }

      // 检验文件类型
      let allowExt = ['jpg', 'jpeg', 'png'],
        ext = file.name.substr(file.name.lastIndexOf('.') + 1);

      if (_.indexOf(allowExt, ext) === -1) {
        layer.msg('文件格式错误,图片格式只能为' + allowExt.toString(), {
          icon: 5
        })

        return
      }

      // 图片大小校验
      let allowWH = new Promise((resolve, reject) => {
        let allowMinWidth = 1280,
          allowMinHeight = 1080,
          oFReader = new FileReader();

        oFReader.readAsDataURL(file)

        oFReader.onload = function (e) {
          let img = new Image()

          img.onload = function () {
            if (img.width < allowMinWidth || img.height < allowMinHeight) {
              reject('图片太小了' + (img.width < allowMinWidth ? ',当前图片宽度为' + img.width + 'px, 允许的最小宽度为' + allowMinWidth + 'px' : '') + (img.height < allowMinHeight ? ',当前图片高度为' + img.height + 'px, 允许的最小高度为' + allowMinHeight + 'px' : ''))
            } else {
              resolve()
            }

          }

          img.onerror = function (e) {
            reject('图片加载异常')
          }

          img.src = e.target.result

        }
      });

      allowWH.then(function () {
        // 文件名称 时间戳 + 6位随机码
        let key = new Date().getTime().toString() + random_string(6) + get_suffix(file.name)

        that.islockImgLock = true;

        let client = new OSS.Wrapper({
          secure: true,
          region: aliyun.region,
          accessKeyId: aliyun.accessKeyId,
          accessKeySecret: aliyun.accessKeySecret,
          bucket: aliyun.bucket
        })

        client.multipartUpload(key, file, {
          progress: function (p) {
            return function (done) {
              that.lockImgProgress = Math.floor(p * 100)
              done()
            }
          }
        }).then(function (res) {
          that.lockImg = key
          that.islockImgLock = false
          that.lockImgProgress = 0
          that.lockImgPreview = previewImg(key, {
            'process': 'image/resize,w_350'
          })

          layer.msg('上传锁屏图片成功', {
            icon: 6
          })

        }).catch(function (err) {
          // console.log(err)
          that.islockImgLock = false
          that.lockImgProgress = 0

          layer.msg('上传锁屏图片失败', {
            icon: 5
          })

        })

      }).catch(function (error) {
        layer.msg(error || '图片异常', {
          icon: 5,
          time: 8000
        })
      })

    },
    // 上传锁屏图片用
    clearImgPreview: function (e) {
      this.lockImgPreview = '';
      this.lockImg = '';
      this.$refs.lockImg.val = '';
    },
    // 获取键盘号或激活码
    getKeyBoardOrPosinfo() {
      let url
      const ytj = ytjKeyboardUrl
      const pos = posKeyboardUrl
      if (this.type === 'pos') {
        url = pos
      }
      if (this.type === 'ytj') {
        url = ytj
      }
      fetch2(url).then(res => {
        this.keyBoardList = res
      })
    },
    // 获取楼盘列表,设置楼盘列表数据
    getBuildingList() {
      fetch2(getBuildListUrl).then(res => {
        if (res) {
          this.buildList = res
        }
      })
    },
    // 获取告知书模版
    getTemplateInfoUrl() {
      fetch2(getTemplateInfoUrl).then(res => {
        this.templetList = res
      })
    },
    // 获取服务类型默认值
    getServiceTypeDefaultData(data) {
      fetch2(getServiceTypeDefaultDataUrl, data).then(res => {
        if (res.object) {
          //  请求回来的值合并给vue实例
          console.log('344', res.object)
          Object.assign(this.$data, res.object)
        }
      })
    },
    // 获取买房协议认购书
    getBuyTemplateList() {
      fetch2(getBuyTemplatUrl).then(res => {
        this.buyTemplateList = res
      })
    }
  }
})

const app = {
  id: getUrlParam('id'),
  type: type,
  staObj: null,
  initTab: null,  // 存放初始状态方法
  controlStr: '',
  storeData: null,
  devInfo: null,  // 设备详细信息
  valid: null, // 存放表单验证方法，添加激活码或启用设备
  init() {
    this.storeData = store.get('storeData')
    this.setTabSta()
  },
  // 获取页面设备分类，根据分类显示不同设置

  // 根据tab状态设置tab
  setTabSta() {
    // 根据状态判断是否显示激活码tab
    if (this.type === 'ytj') {
      $('#dev-code').remove()
    }
    // console.log('tabIndex====>>>', tabIndex)
    switch (tabIndex) {
      case 'code':
        $('.examination-code-body').css('display', 'block')
        this.initTab = this.getCodeInfo
        $('#dev-code').addClass('active-nav')
        break
      case 'history':
        $('.examination-history-body').css('display', 'block')
        this.initTab = this.getHistory
        $('#dev-history').addClass('active-nav')
        break
      default:
        $('.examination-nav-body').css('display', 'block')
        $('#dev-info').addClass('active-nav')
        this.initTab = this.getDetailInfo
    }
    this.initTab()
    this.bindEvent()
  },
  // 获取历史信息
  getHistory() {
    let url = UseHis
    const ytjColumns = [
      {
        field: 'rawAddTime',
        title: '开始时间',
        valign: 'middle',
        formatter: function (index, row) {
          if (row.rawAddTime) {
            const date = new Date(row.rawAddTime)
            return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`
          }
        }
      },
      {
        field: 'rawUpdateTime',
        title: '结束时间',
        valign: 'middle',
        formatter: function (index, row) {
          if (row.rawUpdateTime) {
            const date = new Date(row.rawUpdateTime)
            return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`
          }
        }
      },
      {
        field: 'backup1',
        title: '状态',
        valign: 'middle',
        formatter: function (index, row) {
          const sta = row.backup1 + ''
          let staStr
          switch (sta) {
            case '1':
              staStr = `刚入库`
              break
            case '2':
              staStr = `使用中`
              break
            case '3':
              staStr = `绑定中`
              break
            case '4':
              staStr = `闲置中`
              break
            case '5':
              staStr = `审核中(启用)`
              break
            case '6':
              staStr = `审批中(停用)`
              break
            case '7':
              staStr = `审批中(解绑)`
              break
            case '8':
              staStr = `审核中(启用)`
              break
          }
          return staStr
        }
      },
      {
        field: 'propertyArea',
        title: '区域',
        valign: 'middle',
        formatter: function (index, row) {
          const str = row.propertyArea
          let locationStr
          switch (str) {
            case 'hd':
              locationStr = '华东'
              break
            case 'hn':
              locationStr = '华南'
              break
            case 'hx':
              locationStr = '华西'
              break
            case 'hb':
              locationStr = '华北'
              break
            case 'hz':
              locationStr = '华中'
              break
          }
          return locationStr
        }
      },
      {
        field: 'propertyAddress',
        title: '当前位置',
        valign: 'middle'
      },
      {
        field: 'propertyName',
        title: '服务楼盘',
        valign: 'middle'
      },
      {
        field: 'serviceType',
        title: '服务类型',
        valign: 'middle',
        formatter: function (index, row) {
          const type = row.serviceType
          let typeStr = ''
          switch (type) {
            case "fk":
              typeStr = '付款'
              break
            case "ckzm":
              typeStr = '存款证明'
              break
            case "xf":
              typeStr = '选房'
              break
          }
          return typeStr
        }
      },
      {
        field: 'channel',
        title: '渠道',
        valign: 'middle'
      },
      {
        field: 'mchName',
        title: '商户名称',
        valign: 'middle'
      },
      {
        field: 'keyBoardOrPosinfo',
        title: '键盘号',
        valign: 'middle'
      },
      {
        field: 'requestUserName',
        title: '版本号',
        valign: 'middle'
      },
      {
        field: 'imark',
        title: '备注',
        valign: 'middle'
      }
    ]
    const posColumns = [
      {
        field: 'rawAddTime',
        title: '开始时间',
        valign: 'middle',
        formatter: function (index, row) {
          const date = new Date(row.rawAddTime)
          return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`
        }
      },
      {
        field: 'rawUpdateTime',
        title: '结束时间',
        valign: 'middle',
        formatter: function (index, row) {
          if (row.rawUpdateTime) {
            const date = new Date(row.rawUpdateTime)
            return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`
          }
        }
      },
      {
        field: 'backup1',
        title: '状态',
        valign: 'middle',
        formatter: function (index, row) {
          const sta = row.backup1 + ''
          let staStr
          switch (sta) {
            case '1':
              staStr = `刚入库`
              break
            case '2':
              staStr = `使用中`
              break
            case '3':
              staStr = `绑定中`
              break
            case '4':
              staStr = `闲置中`
              break
            case '5':
              staStr = `审核中(启用)`
              break
            case '6':
              staStr = `审批中(停用)`
              break
            case '7':
              staStr = `审批中(解绑)`
              break
            case '8':
              staStr = `审核中(启用)`
              break
          }
          return staStr
        }
      },
      {
        field: 'propertyArea',
        title: '区域',
        valign: 'middle',
        formatter: function (index, row) {
          const str = row.propertyArea
          let locationStr
          switch (str) {
            case 'hd':
              locationStr = '华东'
              break
            case 'hn':
              locationStr = '华南'
              break
            case 'hx':
              locationStr = '华西'
              break
            case 'hb':
              locationStr = '华北'
              break
            case 'hz':
              locationStr = '华中'
              break
          }
          return locationStr
        }
      },
      {
        field: 'propertyAddress',
        title: '当前位置',
        valign: 'middle'
      },
      {
        field: 'propertyName',
        title: '服务楼盘',
        valign: 'middle'
      },
      {
        field: 'serviceType',
        title: '服务类型',
        valign: 'middle',
        formatter: function (index, row) {
          const type = row.serviceType
          let typeStr = ''
          switch (type) {
            case "fk":
              typeStr = '存转定'
              break
            case "ckzm":
              typeStr = '存款证明'
              break
            case "xf":
              typeStr = '扫码收定金'
              break
          }
          return typeStr
        }
      },
      {
        field: 'channel',
        title: '渠道',
        valign: 'middle'
      },
      {
        field: 'mchName',
        title: '商户名称',
        valign: 'middle'
      },
      {
        field: 'keyBoardOrPosinfo',
        title: '激活码',
        valign: 'middle'
      },
      {
        field: 'imark',
        title: '备注',
        valign: 'middle'
      }
    ]
    let columns
    switch (this.type) {
      case 'ytj':
        columns = ytjColumns
        break
      case 'pos':
        columns = posColumns
        break
    }
    table = $('#history').bootstrapTable($.extend({}, tableConfig, {
      url: base + url,
      queryParams: function (params) {
        return $.extend({
          currentPage: params.pageNumber,
          pageSize: params.pageSize,
        }, { id: app.id })
      },
      ajax: function (params) {  //  自定义ajax
        $.ajax({
          url: params.url,
          type: params.type,
          contentType: params.contentType,
          headers: {
            myToken: Cookies.get('myToken')
          },
          data: params.data
        })
          .done(function (res) {
            console.log("table success", res)

            params.success({
              total: res.object.totalRows,
              rows: res.object instanceof Array ? res.object : res.object.elements
            })

          })
          .fail(function (res) {
            console.log('error====>>', res)
          })

      },
      columns: columns
    }))
  },
  // 获取激活码信息
  getCodeInfo() {
    table = $('#code').bootstrapTable($.extend({}, tableConfig, {
      url: base + codeList,
      queryParams: function (params) {
        return $.extend({
          currentPage: params.pageNumber,
          pageSize: params.pageSize,
        }, $('#searchForm').serializeObject())
      },
      columns: [
        {
          field: 'activation_code',
          title: '激活码',
          valign: 'middle'
        },
        {
          field: 'mch_name',
          title: '商户名称',
          valign: 'middle'
        },
        {
          field: 'mch_No',
          title: '商户号',
          valign: 'middle'
        },
        {
          field: 'pos_term_Id',
          title: '银行终端号',
          valign: 'middle'
        },
        {
          field: 'rawAddTime',
          title: '时间',
          valign: 'middle',
          formatter: function (index, row) {
            const time = row.rawAddTime
            if (time) {
              const date = new Date(time)
              return date.toLocaleDateString()
            }
          }
        },
        {
          field: 'imark',
          title: '备注',
          valign: 'middle'
        },]
    }));
    this.bindCodeEvent()
  },
  bindCodeEvent() {
    // 表单搜索
    $(document).on('click', '#search-btn', () => {
      table.bootstrapTable('refresh', {
        query: $.extend({
          currentPage: 1,
        }, $('#searchForm').serializeObject())
      })
    })
    this.addCode()
  },
  // 添加激活码
  addCode() {
    this.valid = this.codeValid
    this.valid()
    $(document).on('click', '#add-btn', () => {
      $('#code-modal').modal('show')
    })
  },
  // 提交表单，统一调用app里边存放的valid方法，valid方法随时变动
  submitForm(el) {
    app.valid()
    $(el).closest('form').submit()
  },
  // 添加激活码验证
  codeValid() {
    const _form = this

    let form_valid,
      $form = $('#code-form');

    $.validator.setDefaults({ // 只能放在validate规则配置之前

      // 提交事件
      submitHandler: () => {
        console.log('submit!');

        let loading_modal = layer.msg('提交中...', {
          icon: 16,
          time: 0
        });

        // form.isLock = true;
        // console.log('form date:', form)
        let data = $('#code-form').serializeObject()
        console.log('data===>>>823', data)

        // console.log('data data:', data)
        $.ajax({
          type: "POST",
          url: base + addCodeUrl,
          data: data,
          dataType: "json",
          headers: {
            myToken: Cookies.get('myToken')
          },
        })
          .done(function (res) {
            console.log('add code===>>>', res);
            if (res.code === -1) {
              layer.msg(res.message, {
                icon: 5
              });

              return
            }

            layer.msg(`添加成功`, {
              icon: 6
            });

            setTimeout(() => {
              window.location.reload()
            }, 1000)
          })
          .fail(function () {
            layer.msg(`添加失败`, {
              icon: 5
            });
          })

      }
    });

    let validOrderFailureTime
    validOrderFailureTime = _form.isApp
    // 验证
    form_valid = $form.validate({
      errorPlacement: function (error, element) {
        error.appendTo(element.parents('.col-xs-24'))
      },
      rules: {
        activation_code: cusId,
        mch_name: {
          required: true
        },
        serviceType: {
          required: true
        },
        mch_No: cusId // 商户号
      }
    });
  },
  // 获取首页信息栏
  getDetailInfo() {
    fetch2(detailUrl, { id: this.id }).then(res => {
      this.staObj = res.object
      if (res.object) {
        this.initView(res.object)
        vueApp.$data.isPaymentType = res.object.type;
      }
    })
  },
  initView(obj) {
    this.viewDetailInfoTop(obj)
    this.viewControl(obj)
    this.setControlBtn()
  },
  // 设备信息头部信息
  viewDetailInfoTop(obj) {
    console.log('obj===>>>892', obj)
    // 这段代码需要优化 todo
    let type
    const objType = app.type
    vueApp.$data.isPaymentType = obj.type;

    if (objType === 'pos') {
      if ('2' === obj.type) {
        type = '拉卡拉POS'
        $('#dev-code').show();
      }
      if ('3' === obj.type) {
        type = '银商POS'
        $('#dev-code').remove()
      }
    }
    if (objType === 'ytj') {
      type = '一体机'
    }
    // console.log('type==>', type)
    if (type) {
      $('.show-dev-type').text(type)
    }
    // 添加人 equipAddUserName
    if (obj.equipAddUserName) {
      $('.show-dev-addPerson').text(obj.equipAddUserName)
    }
    // 添加 rawAddTime
    if (obj.rawAddTime) {
      const date = new Date(obj.rawAddTime)
      $('.show-dev-addTime').text((date.toLocaleDateString() + date.toLocaleTimeString()))
    }
    if (obj.type === '2' || obj.type === '3') {
      $('.show-dev-terminal').parent().remove()
      // 设备号 identifierCode
      if (obj.identifierCode) {
        $('.show-dev-id').each((index, element) => {
          $(element).text(obj.identifierCode)
        })
      }
    }
    if (obj.type === '1') {
      if (obj.identifierCode) {
        $('.show-dev-id').each((index, element) => {
          $(element).text(obj.identifierCode)
        })
      }
      // 设备号 identifierCode
      if (obj.identifier) {
        $('.show-dev-terminal').each((index, element) => {
          $(element).text(obj.identifier)
        })
      }
    }
    // 当前状态 status
    if (obj.status) {
      // 1:刚入库 2:使用中 3:绑定中 4:闲置中 5:审核中（启用） 6:审核中（停用） 7:审核中（解绑） 8:审核中（启用）",
      let sta
      switch (obj.status) {
        case 1:
          sta = '刚入库'
          break
        case 2:
          sta = '使用中'
          break
        case 3:
          sta = '绑定中'
          break
        case 4:
          sta = '闲置中'
          break
        case 5:
          sta = '审核中（启用）'
          break
        case 6:
          sta = '审核中（停用）'
          break
        case 7:
          sta = '审核中（解绑）'
          break
        case 8:
          sta = '审核中（启用）'
          break
      }
      $('.show-dev-sta').text(sta)
    }
  },
  // 设备操作===》状态闲置中
  viewControl(obj) {
    const sta = obj.status
    let staStr // 需要显示的操作字段
    // 判断是否需要启用设备view
    if (sta == 1 || sta == 4) {
      $('#start-dev').css('display', 'block')
      staStr = '启动设备'
      app.controlStr = '启动'
      this.setViewControlInfo('start-dev', obj, staStr, true)

      // 启用设备触发vue表单
      vueApp.$mount('#start-dev')
      return
    }
    // 状态为使用中，进行停用操作
    if (sta === 2) {
      $('#stop-dev').css('display', 'block')
      staStr = '停用设备'
      this.setViewControlInfo('stop-dev', obj, staStr)
      app.controlStr = '停用'
      return
    }

    // 状态为绑定中，进行解绑操作
    if (sta === 3) {
      $('#unbind-dev').css('display', 'block')
      staStr = '解绑设备'
      app.controlStr = '解绑'
      this.setViewControlInfo('unbind-dev', obj, staStr)
      return
    }

    // 如果处于审核中状态
    switch (sta) {
      case 6:
        staStr = '审核中（停用）'
        break
      case 7:
        staStr = '审核中（解绑）'
        break
      case 5:
      case 8:
        staStr = '审核中（启用）'
        break
    }
    $('#examination').css('display', 'block')
    this.setViewControlInfo('examination', obj, staStr)
    // 判断状态
  },
  // 返回楼盘信息
  setBuildingListView(res) {
    const str = `<option value="${res.id}" data-id="${res.propertyArea}">${res.propertyName}</option>`
    return str
  },
  // 设置底部操作按钮
  setControlBtn() {
    const str = this.controlStr
    if (str) {
      $('#up-control').text(str)
    } else {
      $('#up-control').remove()
    }
  },
  // 删除其他状态的节点只显示当前状态节点
  setViewControlInfo(el, obj, staStr, isStart) {
    if (obj.type == 1) {
      $(`#${el} .type-pos`).remove()
    }
    if (obj.type == 2) {
      $(`#${el} .type-ytj`).remove()
    }
    $('.only-one-status').each((index, element) => {
      if (element.id == el) {
        return
      } else {
        $(element).remove()
      }
    })

    $(`#${el}>p`).text(staStr)
    if (!isStart) {
      fetch2(detailMore, { equipmentId: app.id }).then(res => {
        const arr = ['rawAddTime', 'propertyArea', 'propertyAddress', 'backup1', 'serviceType', 'channel', 'keyBoardOrPosinfo', 'jihuoma', 'versionNumber']
        const info = res.object.elements[0]
        this.devInfo = info
        if (info) {
          arr.map(k => {
            // console.log('k===>>', k)
            if (k === 'propertyArea') {
              let position
              switch (info[k]) {
                case 'hd':
                  position = '华东'
                  break
                case 'hn':
                  position = '华南'
                  break
                case 'hx':
                  position = '华西'
                  break
                case 'hb':
                  position = '华北'
                  break
                case 'hz':
                  position = '华中'
                  break
                default:
                  position = ''
              }
              $(`#${el} .${k}`).text(position ? position : '')
            } else if (k === 'serviceType') {
              const type = app.type
              let serviceType
              switch (info[k]) {
                case 'ckzm':
                  serviceType = '存款证明'
                  break
                case 'fk':
                  if (type === 'pos') {
                    serviceType = '存转定'
                  }
                  if (type === 'ytj') {
                    serviceType = '付款'
                  }
                  break
                case 'xf':
                  if (type === 'pos') {
                    serviceType = '扫码收定金'
                  }
                  if (type === 'ytj') {
                    serviceType = '在线选房'
                  }
                  break
              }
              // console.log('type===>>>', type, 'serviceType===>>>', serviceType)
              $(`#${el} .${k}`).text(serviceType ? serviceType : '')
            }
            else {
              $(`#${el} .${k}`).text(info[k] ? info[k] : '')
            }
          })
        }
      })
    }
  },
  bindEvent() {
    // 顶部操作跳转
    $(document).on('click', '.examination-nav-head', e => {
      const id = $(e.target).attr('data-id')
      location.href = `./detail.html?type=${app.type}&id=${app.id}&tab=${id}`
    })

    // 操作按钮事件
    $(document).on('click', '#up-control', e => {
      const examinationType = app.type
      const toast = $(e.target).text()
      // console.log(toast)
      console.log(vueApp.$data.serviceType)
      const str = `请确认设备${toast}信息`
      const type = $('.show-dev-type').text()
      const id = $('.show-dev-id').text()
      let buildName
      if (vueApp.propertyArea) {
        buildName = vueApp.propertyArea.propertyName
      }
      const keyBoardOrPosinfo = vueApp.keyBoardIdOrPosinfoId
      const keyBoardType = app.type === 'pos' ? '激活码' : '键盘号'
      const midStr = `您正在${toast}<strong style="color:red;">${type}  ${id}</strong> 在 <strong style="color:red;">${buildName ? buildName : ''}</strong> 的服务，请确认是否对该设备进行操作`
      const sta = app.staObj.status
      if (vueApp.$data.isPaymentType !== '3') {
        if (!keyBoardOrPosinfo) {
          // 判断启动状态没有必填信息 isPaymentType =3不验证
          if (sta == 1 || sta == 4) {
            layer.open({
              content: `请完善${keyBoardType}信息`
            })
          }
          return
        }
      }
      if (!buildName) {
        if (sta == 1 || sta == 4) {
          layer.open({
            content: `请完善楼盘信息`
          })
          return
        }
       
        const submitForm = layer.confirm(str, {
          title: str,
          content: midStr,
          btn: ['否', '是'] //按钮
        }, function () {
          layer.close(submitForm)
        }, function () {
          const data = {
            businessId: app.staObj.id,
            approveTitle: `${toast}审批`,
            status: app.staObj.status
          }
          fetch2(startDevUrl, data).then(res => {
            if (res.code == 0) {  // 校验成功
              layer.open({
                content: `${toast}成功`
              }
              )
              location.href = `./index.html?type=${app.type}`
            }
            if (res.code == -1) {
              layer.open({
                title: '设备信息匹配错误',
                content: '配置信息有误，请核查!'
              })
            }
          })
        })
      }
      if (buildName) {
        if(!vueApp.$data.serviceType){
          layer.open({
            content: `请完善服务类型`
          })
          return
        }
        // console.log('1199', buildName)
        const submitForm = layer.confirm(str, {
          title: str,
          content: midStr,
          btn: ['是', '否'] //按钮
        }, function () {
          // console.log(data.keyBoardIdOrPosinfoId)
          if (vueApp.$data.isPaymentType === '3') {
            // 启用设备校验成功，进入启用审批申请流程 //isPaymentType =3不验证,为银商
            app.getStartDevData()
          } else {
            const data = {
              propertyId: vueApp.propertyId,
              keyBoardIdOrPosinfoId: vueApp.keyBoardIdOrPosinfoId,
              serviceType: vueApp.serviceType
            }
            if (examinationType === 'ytj') {
              data.type = 1
            } else {
              data.type = 2
            }
          }
          // console.log('hello===>>>', data)
          fetch2(startValidateUrl, data).then(res => {
            console.log(res)
            console.log(vueApp.$data.isPaymentType)
            if (res.code == 0) {  // 校验成功
              // 启用设备校验成功，进入启用审批申请流程
              app.getStartDevData()
            }
            if (res.code == -1) {
              layer.open({
                title: '设备信息匹配错误',
                content: '配置信息有误，请核查!'
              })
            }
          })

        }, function () {
          layer.close(submitForm)
        })

      }

    }
    )

    // 绑定服务类型选择事件
    // $(document).on('change', '#serviceType', () => {
    //   const val = $('#serviceType option:selected').val()
    //   if (val) {
    //     $('.type-service').css('display', 'none')
    //     $(`.type-${val}`).css('display', 'block')
    //   } else {
    //     $('.type-service').css('display', 'none')
    //   }
    // })
  },
  // 获取启用设备的数据，并提交
  getStartDevData() {
    const obj = {
      serviceType: null,
      cancelDeposit: null,  // 是否支持取消存款证明
      refundReceiveSMSPhone: null,  // 退款通知手机号
      isShowName: null,
      isSignature: null,
      templetId: null,
      ylTicketCount: 1,
      printNum: 1,
      propertyArea: null,
      propertyAddress: null,
      posSignature: null,
      showBankInfo: null,
      voucher: null,
      overdueTime: null,
      orderOverdueTime: null,
      agreement: null,
      keyBoardOrPosinfo: null,
      propertyId: null,
      imark: null,
      keyBoardIdOrPosinfoId: null,
      changePosPay: 0,
      isPrintQRCode: 0,
      changePosLowestMoney: 0,
      isPhotograph: 0,
      isOpenOcr: 0,
    }
    if (app.type === 'ytj') {
      obj.isLock = null

    }

    obj.mchName = null

    const $vueData = vueApp
    const key = Object.keys(obj)

    key.map(list => {
      if ($vueData[list]) {
        obj[list] = $vueData[list]
      }
    })

    if (app.type === 'ytj') {
      obj.keyBoardIdOrPosinfoId = vueApp.keyBoardIdOrPosinfoId
    }

    obj.propertyArea = vueApp.propertyArea.propertyArea
    obj.propertyAddress = vueApp.propertyArea.propertyName

    if (obj.isLock == 1) {
      obj.lockImg = vueApp.lockImgPreview
      obj.lockTime = vueApp.lockTime
    }
    obj.businessId = app.id
    obj.status = app.staObj.status
    obj.approveTitle = '启动设备'

    //zhanghong 
    console.log('启动设备', obj)
    // 传送设备
    fetch2(startDevUrl, obj).then(res => {
      if (res.object.code == 0) {
        layer.open({
          content: '启动设备成功'
        })
        //zhanghong
        console.log('1312', res)
        location.href = `./index.html?type=${app.type}`
      }
    })
  },
  // 绑定tab栏样式
  bindStyle() {
    $(`#${this.examinationType}`).addClass('active')
  }
}
app.init()

